package com.example.novelweb.controller;

import com.example.novelweb.common.BaseResponse;
import com.example.novelweb.common.ResultUtils;
import com.example.novelweb.model.vo.NovelVO;
import com.example.novelweb.service.NovelService;
import com.example.novelweb.service.RedisService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/recommend")
public class RecommendController {
  @Resource
  private NovelService novelService;

  @Resource
  private RedisService redisService;

  @GetMapping("/max-collects")
  public BaseResponse<List<NovelVO>> listMaxCollects(Integer limit, HttpServletRequest httpServletRequest) {
    if(redisService.hasCacheTopCollects()) {
      List<NovelVO> cache = redisService.getCacheTopCollects();
      if(!cache.isEmpty()) {
        return ResultUtils.success(cache);
      }
    }
    synchronized (this) {
      if(redisService.hasCacheTopCollects()) {
        List<NovelVO> cache = redisService.getCacheTopCollects();
        if(!cache.isEmpty()) {
          return ResultUtils.success(cache);
        }
      }

      if(limit <5) limit= 5;
      else if(limit >10) limit = 10;
      List<NovelVO> items = novelService.listMaxCollects(limit);

      redisService.setCacheTopCollects(items);
      return ResultUtils.success(items);
    }

  }
}
